/*
 *  @Description:
 *  * @since:         2023/5/4 上午9:53
 *  * @author:       瓦尔
 *
 */
package com.wal.aiclient.common;

import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Component
public class PythonServiceClient {
    private  String pythonUrl;

    public PythonServiceClient(){}
    public PythonServiceClient(String pythonUrl) {
        this.pythonUrl = pythonUrl;
    }

    public String translate(String text) throws Exception {
        // 发送POST请求
        HttpURLConnection conn = (HttpURLConnection) new URL(pythonUrl).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        os.write(text.getBytes(StandardCharsets.UTF_8));
        os.flush();
        os.close();

        // 读取Python服务的响应
        InputStream is = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        conn.disconnect();

        // 解析Python服务的响应
        String translatedText = parseResponse(response.toString());

        return translatedText;
    }

    private String parseResponse(String response)  {
        // 这里可以根据实际情况解析Python服务的响应，这里简单地将响应解析成JSON格式并返回翻译结果
        JSONObject json = new JSONObject(response);
        String translatedText = json.getStr("result");
        return translatedText;
    }

    public static void main(String[] args) {
//        String pythonUrl = "http://localhost:8888/ai"; // Python服务的URL
        String pythonUrl = "http://11.11.115.136:8888/ai"; // Python服务的URL
        PythonServiceClient client = new PythonServiceClient(pythonUrl);
        String text = "美酒佳肴"; // 要翻译的文本
        try {
            String result = client.translate(text);
            System.out.println("计算结果：" + result);
        } catch (Exception e) {
            System.out.println("计算出错：" + e.getMessage());
        }
    }

}
